// cnpm install socket.io express
const http = require("http");
const express = require("express");
const socketIo = require("socket.io");
const app = express();
const httpServer = http.createServer(app);
const io = socketIo(httpServer);// 创建一个基于webSocket的服务
const userList = {};
io.on("connection",function(socket){
	console.log("连接socket服务",socket.id);
	socket.on("intoRoom",function(userName){
		userList[socket.id] = userName;
		io.emit("inlineNum",userName,Object.keys(userList).length,true);
	})
	
	socket.on("disconnect",function(){
		const userName = userList[socket.id];
		delete userList[socket.id];
		io.emit("inlineNum",userName,Object.keys(userList).length,false);
		console.log("断开连接",socket.id);
	})
	
	socket.on("say",function(userName,sayText){
		io.emit("roomSay",userName,sayText);
	})
})
app.use(express.static(__dirname));
app.get("/login",(req,res)=>{
	const userName = req.query.userName;
	if(Object.values(userList).includes(userName)){
		res.json({
			ok:-1
		})
	}else{
		res.json({
			ok:1
		})
	}
	
})
httpServer.listen(80,function(){
	console.log("success");
})